<?php

namespace app\common\model;

use think\Model;

class Address extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 定义字段类型
    protected $type = [
    ];
    protected $append = [
    ];

    /**
     * 获取列表
     */
    public function getList($applet_user_id=0)
    {
        // 筛选条件
        $filter = [];
        $applet_user_id > 0 && $filter['applet_user_id'] = $applet_user_id;
        // 执行查询
        return $this->where($filter)
            ->order('id','desc')
            ->select();
    }

    /**
     * 新增收货地址
    */ 
    public function add($user, $data)
    {
        // 添加收货地址
        $data['applet_user_id'] = $user['id'];
        $this->allowField(true)->save($data);
        // 设为默认收货地址
        !$user['address_id'] && $user->allowField(true)->save(['address_id' => $this->getLastInsID()]);
        return true;
    }
    
    
    /**
     * 编辑地址
    */
    public function edit($data)
    {
        return $this->allowField(true)->save($data) !== false;
    }

    /**
     * 设为默认收货地址
     */
    public function setDefault($user)
    {
        // 设为默认地址
        return $user->allowField(true)->save(['address_id' => $this['id']]);
    }

    /**
     * 删除收货地址
     */
    public function remove($user)
    {
        // 查询当前是否为默认地址
        $user['address_id'] == $this['id'] && $user->allowField(true)->save(['address_id' => 0]);
        return $this->delete();
    }
}
